package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.utils.IdGenerator;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@Service
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdGenerator idGenerator;
    @Override
    public String save(Video video) {

        video.setVid(idGenerator.nextId("video"));
        video.setCreated(System.currentTimeMillis());
        video.setText("1234567890-");
        mongoTemplate.insert(video);
        return video.getId().toHexString();
    }

    @Override
    public PageResult videoList(Integer page,Integer pagesize) {
        Query query = new Query();
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page,pagesize));
        List<Video> videos = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);
        int pages = (int) Math.ceil(count*1.0/pagesize);
        return new PageResult((int) count,pagesize,pages,page,videos);
    }

    @Override
    public void focus(Long userId,Long uid) {
        FollowUser followUser = new FollowUser();
        followUser.setUserId(userId);
        followUser.setFollowUserId(uid);
        followUser.setCreated(System.currentTimeMillis());

        mongoTemplate.insert(followUser);
    }

    @Override
    public void unFocus(Long userId, Long uid) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("followUserId").is(uid));
        mongoTemplate.remove(query,FollowUser.class);
    }

    @Override
    public PageResult findVideoList(Long uid, int page, int pagesize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(uid));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page-1,pagesize));
        List<Video> videos = mongoTemplate.find(query, Video.class);
        int count = (int) mongoTemplate.count(query, Video.class);
        int pages = (int) Math.ceil(count*1.0/pagesize);
        return new PageResult(count,pagesize,pages,page,videos);
    }

    @Override
    public Video findVideoById(Long videoId) {
        return mongoTemplate.findById(videoId,Video.class);
    }
}
